package org.gangcai.mac.shop.fragment;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.activity.ShopDetailActivity;
import org.gangcai.mac.shop.adapter.MultipleItemQuickAdapter;
import org.gangcai.mac.shop.adapter.PullToRefreshAdapter;
import org.gangcai.mac.shop.api.AppAPI;
import org.gangcai.mac.shop.bean.DataServer;
import org.gangcai.mac.shop.bean.DynamicBean;
import org.gangcai.mac.shop.bean.HomeIndexBean;
import org.gangcai.mac.shop.bean.IndexBean;
import org.gangcai.mac.shop.bean.RecommendBean;
import org.gangcai.mac.shop.bean.UpdateShopData;
import org.gangcai.mac.shop.constants.Constant;
import org.gangcai.mac.shop.entity.MultipleItem;
import org.gangcai.mac.shop.manager.RetrofitManagers;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.rxlife.RxFragment;
import org.gangcai.mac.shop.utils.PromptDialogUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.leefeng.promptlibrary.PromptDialog;

/**
 * 商品界面
 */
public class DynamicFragment extends RxFragment implements MultiItemTypeAdapter.OnItemClickListener, PullToRefreshAdapter.ShareDynamicClickListener, OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    Unbinder unbinder;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.main_content)
    CoordinatorLayout mainContent;
    ArrayList<IndexBean.InfoBean> datalist = new ArrayList<>();
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String mParam1;
    private String mParam2;
    private CommonAdapter<IndexBean.InfoBean> adapter;
    private PromptDialog prompDialog;
    private PullToRefreshAdapter mAdapter;
    private static final int PAGE_SIZE = 6;
    private int mNextRequestPage = 1;
    private int imageNumber = 0;
    private int fileCount = 0;
    private String kDescription = "姝雅瑞";
    private static final String LOG_TAG = "ImageDownloader";
    private String house_id = null;
    private List<File> files;
    private FinalHttp fh;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    prompDialog.showLoading("请耐心等待...");
                    GetShareImageTask shareTask1 = new GetShareImageTask();
                    shareTask1.execute();
                    break;
            }
        }
    };

    public DynamicFragment() {
    }

    public static DynamicFragment newInstance(String param1, String param2) {
        DynamicFragment fragment = new DynamicFragment();
        Bundle args = new Bundle();
        args.putString( ARG_PARAM1, param1 );
        args.putString( ARG_PARAM2, param2 );
        fragment.setArguments( args );
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        if (getArguments() != null) {
            mParam1 = getArguments().getString( ARG_PARAM1 );
            mParam2 = getArguments().getString( ARG_PARAM2 );
        }
        EventBus.getDefault().register( this );
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate( R.layout.fragment_dynamic, container, false );
        unbinder = ButterKnife.bind( this, view );
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated( view, savedInstanceState );
        prompDialog = PromptDialogUtils.getPrompDialog( getActivity() );
        recyclerview.setLayoutManager( new LinearLayoutManager( getActivity() ) );
        initAdapter();
        loadData();
    }

    private void initAdapter() {
        mAdapter = new PullToRefreshAdapter( getActivity(),this );
        mAdapter.setOnLoadMoreListener( new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        } );
//        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
//        mAdapter.setPreLoadNumber(3);
        recyclerview.setAdapter( mAdapter );

        recyclerview.addOnItemTouchListener( new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {
//                Toast.makeText( getActivity(), Integer.toString( position ), Toast.LENGTH_LONG ).show();
            }
        } );
    }


    private void loadMore() {
        RetrofitManagers.getInstance().create( AppAPI.class ).dynamic( "dynamic", String.valueOf( mNextRequestPage ) )
                .observeOn( AndroidSchedulers.mainThread() )
                .compose( this.<DynamicBean>bindToLifecycle() )
                .subscribe( new CommonObserver<DynamicBean>( refreshLayout ) {
                    @Override
                    public void onSuccess(DynamicBean value) {
                        if (value.getCode() == 101) {
                            setData( false, value.getInfo() );
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError( e );
                        mAdapter.loadMoreFail();
                        Toast.makeText( getActivity(), R.string.network_err, Toast.LENGTH_LONG ).show();
                    }
                } );
    }

    private void setData(boolean isRefresh, List data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData( data );
        } else {
            if (size > 0) {
                mAdapter.addData( data );
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd( isRefresh );
            Toast.makeText( getActivity(), "no more data", Toast.LENGTH_SHORT ).show();
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    private void loadData() {
        LogUtils.e( "loadDynamicFragment" );
        mNextRequestPage = 1;
        RetrofitManagers.getInstance().create( AppAPI.class ).dynamic( "dynamic", "0" )
                .observeOn( AndroidSchedulers.mainThread() )
                .compose( this.<DynamicBean>bindToLifecycle() )
                .subscribe( new CommonObserver<DynamicBean>( refreshLayout ) {
                    @Override
                    public void onSuccess(DynamicBean value) {
                        if (value.getCode() == 101) {
                            setData( true, value.getInfo() );
                            mAdapter.setEnableLoadMore( true );
                        }
                    }


                } );
    }

    private void initView() {
        adapter = new CommonAdapter<IndexBean.InfoBean>( this.getContext(), R.layout.fragment_shop_recyclerview_item, datalist ) {
            @Override
            protected void convert(ViewHolder holder, IndexBean.InfoBean o, int position) {

                Glide.with( DynamicFragment.this ).load( Constant.IMAGE_PATH + o.getImg() ).into( (ImageView) holder.getView( R.id.squareIv ) );
                holder.setText( R.id.goodMoney, o.getMoney() );
                holder.setText( R.id.goodTitle, o.getGoods_name() );
            }

        };
        recyclerview.setLayoutManager( new GridLayoutManager( this.getContext(), 2 ) );
        recyclerview.setAdapter( adapter );
        adapter.setOnItemClickListener( this );
        refreshLayout.setEnableLoadmore( false );
        refreshLayout.setEnableRefresh( true );
        refreshLayout.setOnRefreshListener( this );
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister( this );
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        Bundle bundle = new Bundle();
        bundle.putString( "id", datalist.get( position ).getId() );
        ActivityUtils.startActivity( bundle, this.getActivity(), ShopDetailActivity.class );
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    @Subscribe
    public void onEvent(UpdateShopData data) {
        loadData();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        loadData();
    }

    @Override
    public void shareDynamicWithComment(DynamicBean.DynamicInfoBean item) {
        prompDialog.showLoading("请耐心等待...");
        files = new ArrayList<File>();
        house_id=item.getId();
        imageNumber = 0;
        fileCount = 0;
        kDescription=item.getContent();
        String savePath = null;
        if (hasSdcard()) {
            savePath = Environment.getExternalStorageDirectory()
                    + File.separator + LOG_TAG + File.separator
                    + "shareImage_" + house_id + "_" + imageNumber
                    + ".jpg";
        } else {
            savePath = Environment.getDownloadCacheDirectory()
                    + File.separator + "shareImage_" + house_id
                    + "_" + imageNumber + ".jpg";
        }
        File file = new File( savePath );
        if (item.getImg_list() != null && item.getImg_list().size() > 0) {
            for (int i = 0; i < item.getImg_list().size(); i++) {
                files.add( file );
            }
            for (int i = 0; i < item.getImg_list().size(); i++) {
                String img_path = item.getImg_list().get( i ).getImg_path();
                String imageUrl = Constant.IMAGE_PATHS + img_path.substring(3);
                saveImage( imageUrl, i );
            }
        }

    }

    class GetShareImageTask extends AsyncTask<String, String, String> {
        private String jsonString = null;

        protected String doInBackground(String... param) {
            return jsonString;
        }

        protected void onPostExecute(String result) {
        }
    }

    public boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals( Environment.MEDIA_MOUNTED )) {
            return true;
        } else {
            return true;
        }
    }

    private void saveImage(String imageUrl, final int position) {
        String savePath = null;
        if (hasSdcard()) {
            savePath = Environment.getExternalStorageDirectory()
                    + File.separator + LOG_TAG + File.separator + "shareImage_"
                    + house_id + "_" + imageNumber + ".jpg";
        } else {
            savePath = Environment.getDownloadCacheDirectory() + File.separator
                    + "shareImage_" + house_id + "_" + imageNumber + ".jpg";
        }
        File file = new File( savePath );
            if (file.exists()) {
                try {
                    MediaStore.Images.Media.insertImage( getActivity().getContentResolver(), savePath, UUID.randomUUID().toString() + ".jpg", UUID.randomUUID().toString() );
                    getActivity().sendBroadcast( new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile( file ) ) );

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            files.set( position, file );
            fileCount++;
            if (fileCount == files.size() - 1) {
                prompDialog.dismiss();
                Toast.makeText( getActivity(), "下载完成,准备分享...分享标题已复制，请长按复制粘贴...",
                        Toast.LENGTH_SHORT ).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction( Intent.ACTION_SEND_MULTIPLE );
                sendIntent.setType( "image/*" );
                sendIntent.putExtra( "Kdescription", kDescription );
                sendIntent.putExtra( Intent.EXTRA_TEXT, kDescription );
                ComponentName comp = null;
                ArrayList<Uri> uris = new ArrayList<Uri>();
                for (File f : files) {
                    Uri uri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//24
                        uri = FileProvider.getUriForFile( getActivity(), "org.gangcai.mac.shop.fileprovider", f );
                        ContentResolver cR = getActivity().getContentResolver();
                        if (uri != null && uri.toString().length() > 0) {
                            String fileType = cR.getType( uri );
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
                            if (fileType.length() > 0) {
                                if (fileType.contains( "video/" )) {
                                    uri = getVideoContentUri( getActivity(), f );
                                } else if (fileType.contains( "image/" )) {
                                    uri = getImageContentUri( getActivity(), f );
                                } else if (fileType.contains( "audio/" )) {
                                    uri = getAudioContentUri( getActivity(), f );
                                }
                            }
                        }
                        Log.d( "***uri***", uri.toString() );
                    } else {
                        uri = Uri.fromFile( f );
                    }
                    uris.add( uri );
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    ClipboardManager cm = (ClipboardManager) getActivity().getSystemService( Context.CLIPBOARD_SERVICE );
                    ClipData mClipData = ClipData.newPlainText( "Label", kDescription );
                    cm.setPrimaryClip( mClipData );
                }
                sendIntent.putParcelableArrayListExtra( Intent.EXTRA_STREAM,
                        uris );
                sendIntent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
                sendIntent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
                comp = new ComponentName( "com.tencent.mm",
                        "com.tencent.mm.ui.LauncherUI" );
//                com.tencent.mm.ui.tools.ShareToTimeLineUI
                sendIntent.setComponent( comp );
                startActivity( sendIntent );

            }
        } else {
            fh = new FinalHttp();
                final String finalSavePath = savePath;
                fh.download( imageUrl, savePath, new AjaxCallBack<File>() {
                @Override
                public void onStart() {
                    super.onStart();
                    // Toast.makeText(getApplicationContext(), "开始下载" +
                    // imageNumber,
                    // Toast.LENGTH_SHORT).show();
                }

                @SuppressLint("DefaultLocale")
                @Override
                public void onLoading(long count, long current) {
                    super.onLoading( count, current );
                }

                @Override
                public void onSuccess(File t) {
                    super.onSuccess( t );
                    try {
                        MediaStore.Images.Media.insertImage( getActivity().getContentResolver(), finalSavePath, UUID.randomUUID().toString() + ".jpg", UUID.randomUUID().toString() );
                        getActivity().sendBroadcast( new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile( t ) ) );

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
//                    try {
//                        MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), t.getPath(), "title", "description");
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
                    // Toast.makeText(getApplicationContext(), "下载完成" +
                    // imageNumber,
                    // Toast.LENGTH_SHORT).show();
                    files.set( position, t );
                    fileCount++;
                    if (fileCount == files.size() - 1) {
                        prompDialog.dismiss();
                        Toast.makeText( getActivity(), "下载完成,准备分享...分享标题已复制，请长按复制粘贴...",
                                Toast.LENGTH_SHORT ).show();
                        Intent sendIntent = new Intent();
                        sendIntent.setAction( Intent.ACTION_SEND_MULTIPLE );
                        sendIntent.setType( "image/*" );
                        sendIntent.putExtra( "Kdescription", kDescription );
                        sendIntent
                                .putExtra( Intent.EXTRA_TEXT, kDescription );
                        ArrayList<Uri> uris = new ArrayList<Uri>();
                        for (File f : files) {
                            Uri uri = null;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//24
                                uri = FileProvider.getUriForFile( getActivity(), "org.gangcai.mac.shop.fileprovider", f );
                                ContentResolver cR = getActivity().getContentResolver();
                                if (uri != null && uri.toString().length() > 0) {
                                    String fileType = cR.getType( uri );
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
                                    if (fileType.length() > 0) {
                                        if (fileType.contains( "video/" )) {
                                            uri = getVideoContentUri( getActivity(), f );
                                        } else if (fileType.contains( "image/" )) {
                                            uri = getImageContentUri( getActivity(), f );
                                        } else if (fileType.contains( "audio/" )) {
                                            uri = getAudioContentUri( getActivity(), f );
                                        }
                                    }
                                }
                                Log.d( "***uri***", uri.toString() );
                            } else {
                                uri = Uri.fromFile( f );
                            }
                            uris.add( uri );
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService( Context.CLIPBOARD_SERVICE );
                            ClipData mClipData = ClipData.newPlainText( "Label", kDescription );
                            cm.setPrimaryClip( mClipData );
                        }
                        sendIntent.putParcelableArrayListExtra(
                                Intent.EXTRA_STREAM, uris );
                        ComponentName comp = new ComponentName(
                                "com.tencent.mm",
                                "com.tencent.mm.ui.LauncherUI" );
                        sendIntent.setComponent( comp );
                        sendIntent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );    //这一步很重要。给目标应用一个临时的授权。
                        startActivity( sendIntent );
                    }
                    // Intent intent = new
                    // Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    // Uri uri = Uri.fromFile(t);
                    // intent.setData(uri);
                    // ShareActivity.this.sendBroadcast(intent);
                }

                @Override
                public void onFailure(Throwable t, String strMsg) {
                    // TODO Auto-generated method stub
                    super.onFailure( t, strMsg );
                    // Toast.makeText(getApplicationContext(), "下载失败" +
                    // imageNumber,
                    // Toast.LENGTH_SHORT).show();
                }

            } );
        }
        imageNumber++;
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param imageFile
     * @return content Uri
     */
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param videoFile
     * @return content Uri
     */
    public static Uri getVideoContentUri(Context context, File videoFile) {
        String filePath = videoFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Video.Media._ID }, MediaStore.Video.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/video/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (videoFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Video.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param audioFile
     * @return content Uri
     */
    public static Uri getAudioContentUri(Context context, File audioFile) {
        String filePath = audioFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Audio.Media._ID }, MediaStore.Audio.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/audio/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (audioFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Audio.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

}
